const app = getApp()

Page({
  data: {
    exams: [],
    page: 1,
    perPage: 10,
    hasMore: true,
    loading: false,
    refreshing: false
  },

  onLoad() {
    this.loadExams()
  },

  onShow() {
    // 页面显示时刷新数据
    this.refreshData()
  },

  onPullDownRefresh() {
    this.refreshData()
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMore()
    }
  },

  // 加载考试列表
  loadExams(refresh = false) {
    if (this.data.loading) return

    this.setData({ loading: true })

    const params = {
      page: refresh ? 1 : this.data.page,
      per_page: this.data.perPage
    }

    wx.request({
      url: `${app.globalData.baseUrl}/exams/`,
      method: 'GET',
      data: params,
      header: {
        'Authorization': `Bearer ${app.globalData.token}`
      },
      success: (res) => {
        if (res.data.success) {
          const newExams = res.data.data.items
          const total = res.data.data.total
          const currentPage = res.data.data.page
          const hasMore = currentPage * this.data.perPage < total

          this.setData({
            exams: refresh ? newExams : [...this.data.exams, ...newExams],
            page: currentPage + 1,
            hasMore: hasMore,
            loading: false,
            refreshing: false
          })

          if (refresh) {
            wx.stopPullDownRefresh()
          }
        } else {
          wx.showToast({
            title: res.data.message || '加载失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('加载考试失败:', err)
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
        this.setData({ 
          loading: false, 
          refreshing: false 
        })
        if (refresh) {
          wx.stopPullDownRefresh()
        }
      }
    })
  },

  // 加载更多
  loadMore() {
    this.loadExams()
  },

  // 刷新数据
  refreshData() {
    this.setData({
      refreshing: true,
      page: 1,
      hasMore: true
    })
    this.loadExams(true)
  },

  // 跳转到考试详情
  goToExam(e) {
    const examId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/exam-detail/exam-detail?id=${examId}`
    })
  },

  // 开始考试
  startExam(e) {
    const examId = e.currentTarget.dataset.id
    
    // 检查用户是否已登录
    if (!app.globalData.userInfo) {
      wx.showModal({
        title: '提示',
        content: '请先登录后再参加考试',
        showCancel: false
      })
      return
    }

    // 检查是否已经参加过该考试
    wx.request({
      url: `${app.globalData.baseUrl}/exams/${examId}/check-participation`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${app.globalData.token}`
      },
      success: (res) => {
        if (res.data.success) {
          if (res.data.data.has_participated) {
            wx.showModal({
              title: '提示',
              content: '您已经参加过该考试，是否查看考试结果？',
              success: (modalRes) => {
                if (modalRes.confirm) {
                  wx.navigateTo({
                    url: `/pages/exam-result/exam-result?exam_id=${examId}`
                  })
                }
              }
            })
          } else {
            // 开始考试
            wx.navigateTo({
              url: `/pages/exam-detail/exam-detail?id=${examId}&start=true`
            })
          }
        } else {
          wx.showToast({
            title: res.data.message || '检查失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('检查考试参与状态失败:', err)
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
      }
    })
  }
}) 